package org.vyana.control {
	
	import flash.utils.Dictionary;
	import flash.utils.getQualifiedClassName;
	
	import mx.utils.DescribeTypeCache;
	
	import org.vyana.control.commands.ICommand;
	import org.vyana.model.constant.VyanaMessageCodes;

	public class VyanaController {
		
		protected var commands:Dictionary = new Dictionary();

		protected function get context():VyanaContext {
			return VyanaContext.getInstance();
		}

		public function addCommandRegistry(commandRegistryClass:Class):void {			
			if (!commandRegistryClass) 
				return;

			for each (var cmdAlias:String in DescribeTypeCache.describeType(commandRegistryClass).typeDescription..constant.@name) {
				var cmdUId:String = getQualifiedClassName(commandRegistryClass[cmdAlias]);
				
//				if (commands[cmdUId])
//					throw new VyanaError(VyanaMessageCodes.COMMAND_ALREADY_REGISTERED, cmdUId);
				 				
				commands[cmdUId] = commandRegistryClass[cmdAlias];

				context.addEventListener(cmdUId, executeCommand, false, 0, true);
			}

		}

		/**
		 * Executes the command
		 */  
		protected function executeCommand(event:VyanaEvent):void {
			var commandToInitialise:Class = getCommand(event.type);
			var commandToExecute:ICommand = new commandToInitialise();

			commandToExecute.execute(event);
		}

		/**
		 * Returns the command class registered with the command name. 
		 */
		protected function getCommand(commandName:String):Class {
			var command:Class = commands[commandName];

			if (!command)
				throw new Error(VyanaMessageCodes.COMMAND_NOT_FOUND, commandName);

			return command;
		}

	}
}